import {defineStore} from 'pinia'
import {getToken, setToken, removeToken} from '@/utils/token'
import {ElMessageBox} from 'element-plus'
import router from '@/router'
import { getUserInfoMockApi, loginMockApi } from '@/api/mock-js/login-api'

const useLoginStore = defineStore('loginStore', {
    state: () => ({
        token: getToken(),
        // 用户个人信息
        userInfo: {}
    }),
    actions: {
        // 获取用户信息
        async getUserInfo() {
            try {
                const res = await getUserInfoMockApi()
                this.userInfo = res.data
                if ( !res.data?.roleAndPermissions?.length) {
                    ElMessageBox.confirm('该用户没有任何权限，请联系管理员！').then(()=>{
                        this.logout()
                        router.push('/login').then()
                    })
                    return false
                }
            } catch (e) {
            }
        },
        // 登录，获取token,根据token请求用户信息
        async handleLogin(formData) {
            try {
                const res = await loginMockApi(formData)
                setToken(res.data)
                await this.getUserInfo()
            } catch (e) {
            }
        },
        // 退出登录
        logout() {
            this.userInfo = {}
            removeToken()
        }
    }
})
export default useLoginStore
